package com.atguigu.e_reflect.field;

import java.lang.reflect.Field;

public class Demo1 {
    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
        //反射第一步 : 获取类的字节码对象
        Student stu = new Student();
        Class<? extends Student> clazz = stu.getClass();

        //获取指定的成员变量对象
        Field name = clazz.getDeclaredField("name");
        System.out.println("name = " + name);
        //设置值
        name.set(stu,"张三"); //stu.name = "张三;
        //获取值
        System.out.println("name.get(stu) = " + name.get(stu));//张三

        System.out.println("----------------------------------");

        Field age = clazz.getDeclaredField("age");
        System.out.println("age = " + age);
        //设置值
        age.set(stu,18);
        //获取值
        System.out.println("age.get(stu) = " + age.get(stu));//18

        System.out.println("----------------------------------");

        Field gender = clazz.getDeclaredField("gender");
        System.out.println("gender = " + gender);
        //设置值
        gender.set(stu,"男");
        //获取值
        System.out.println("gender.get(stu) = " + gender.get(stu));//男

        System.out.println("----------------------------------");

        Field salary = clazz.getDeclaredField("salary");
        System.out.println("salary = " + salary);
        //因为是私有属性 所以没有访问权限 -> 开启暴力反射开关
        salary.setAccessible(true);

        //设置值
        salary.set(stu,20000);

        //获取值
        System.out.println("salary.get(stu) = " + salary.get(stu));

        System.out.println("----------------------------------");

        Student stu1 = new Student();
        System.out.println("stu1.name = " + stu1.name);//null
        System.out.println("stu1.age = " + stu1.age);//0
        System.out.println("stu1.gender = " + stu1.gender);//null
        //System.out.println("stu1.salary = " + stu1.salary); -> 不是反射代码 获取不到类中私有属性
    }
}
